package org.idea.qiyu.framework.web.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.idea.qiyu.framework.web.model.IResponseVO;
import org.idea.qiyu.framework.web.model.MessageResponseVO;
import org.idea.qiyu.framework.web.model.WebJsonBean;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

/**
 * @Author linhao
 * @Date created in 12:26 下午 2021/8/31
 */
public class QiyuReturnValueHandler implements HandlerMethodReturnValueHandler {

    private RequestResponseBodyMethodProcessor target;

    public QiyuReturnValueHandler(RequestResponseBodyMethodProcessor target) {
        this.target = target;
    }

    @Override
    public boolean supportsReturnType(MethodParameter methodParameter) {
        return true;
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest) throws Exception {
        if (returnType == null) {
            return;
        }
        if(IResponseVO.class.isAssignableFrom(returnType.getParameterType())){
            IResponseVO response = (IResponseVO) returnValue;
            WebJsonBean webJsonBean = WebJsonBean.success();
            if(response instanceof MessageResponseVO){
                webJsonBean.setData(((MessageResponseVO) response).getMsg());
            }
            String json = JSON.toJSONString(webJsonBean, SerializerFeature.WriteMapNullValue);
            target.handleReturnValue(json,returnType,modelAndViewContainer,nativeWebRequest);
        } else {
            target.handleReturnValue(returnValue,returnType,modelAndViewContainer,nativeWebRequest);
        }
    }


}
